'use strict'

const Controller = require('egg').Controller
const fs = require('mz/fs')
const path = require('path')
const { getRecentMonths } = require('../utils/common')

class CommonController extends Controller {
  // 上传文件
  async upload() {
    const { ctx } = this
    if (!ctx.request.files) {
      return ctx.apiFail('请先选择上传文件')
    }
    const file = ctx.request.files[0]
    // 获取文件名
    const name = ctx.genID(10) + path.extname(file.filename)
    let result
    try {
      // 上传oss
      result = await ctx.oss.put(name, file.filepath)
    } catch (err) {
      return ctx.apiFail('上传失败')
    } finally {
      await fs.unlink(file.filepath)
    }
    if (result) {
      // 返回结果
      return ctx.apiSuccess(result.url)
    }
    ctx.apiFail('上传失败')
  }
  // 删除文件
  async deleteFile() {
    const { ctx } = this
    // 参数验证
    ctx.validate({ name: { type: 'string', required: true, desc: '文件链接' } })
    const { name } = ctx.request.body
    if (!name.startsWith('http')) return ctx.apiFail('文件链接错误')

    // 获取文件名称
    const fileName = name.substring(name.lastIndexOf('/') + 1)
    try {
      // oss
      await ctx.oss.delete(fileName)
      ctx.apiSuccess('删除成功')
    } catch (err) {
      ctx.apiFail('删除失败')
    }
  }
  // 获取工作台数据
  async getWorkbenchData() {
    const { ctx, app } = this
    // 访问总数
    const visit_count = await app.model.Visit.findOne()
    // 用户总数
    const user_count = await app.model.User.count()
    // 留言总数
    const leaveword_count = await app.model.Leaveword.count()
    // 留言墙总数
    const leaveword_wall_count = await app.model.Leaveword.count({ where: { wall_id: 1 } })
    // 照片墙总数
    const image_wall_count = await app.model.Leaveword.count({ where: { wall_id: 2 } })

    // 最近12个月留言数量
    const Op = app.Sequelize.Op
    const recentMonths = getRecentMonths().reverse()
    const y_user = []
    const y_tourist = []
    for (let index = 0; index < recentMonths.length; index++) {
      // 起始月
      const startOfMonth = new Date(`${recentMonths[index]}-01T00:00:00Z`)
      // 下一个月
      const nextMonth = new Date(`${recentMonths[index]}-01T00:00:00Z`)
      const endOfMonth = new Date(nextMonth.setMonth(nextMonth.getMonth() + 1))
      // 用户留言数量
      const user_leaveword_count = await app.model.Leaveword.count({
        where: { created_time: { [Op.gte]: startOfMonth, [Op.lt]: endOfMonth } },
        include: [{ model: app.model.User, where: { type: 1 } }]
      })
      // 游客留言数量
      const tourist_leaveword_count = await app.model.Leaveword.count({
        where: { created_time: { [Op.gte]: startOfMonth, [Op.lt]: endOfMonth } },
        include: [{ model: app.model.User, where: { type: 2 } }]
      })
      y_user.push(user_leaveword_count)
      y_tourist.push(tourist_leaveword_count)
    }

    // 最近7条举报
    const report = await app.model.Feedback.findAll({
      where: { type: 2 },
      order: [['id', 'DESC']],
      limit: 7,
      include: [
        {
          model: app.model.Leaveword,
          attributes: ['name', 'content']
        }
      ]
    })

    const responseData = {
      user_count,
      leaveword_count,
      leaveword_wall_count,
      image_wall_count,
      visit_count: visit_count.count,
      x_month: recentMonths,
      y_user,
      y_tourist,
      report
    }
    ctx.apiSuccess(responseData)
  }
}

module.exports = CommonController
